<script setup>
import { ref, nextTick } from 'vue'
import {
  getHasTrademarkAPI,
  addorUpdateTrademarkAPI,
  deleteTrademarkAPI,
} from '@/api/product/tradeMark'
import { ElMessage } from 'element-plus'

// 当前页码
const pageNo = ref(1)
// 每一页展示多少数据
const limit = ref(3)
// 表格数据
const trademarkArr = ref([])
// 总共多少数据
const total = ref(0)
// 对话框显示与隐藏
const dialogShowFlag = ref(false)
// 定义收集新增品牌数据
const trademarkParams = ref({
  tmName: '',
  logoUrl: '',
})
// 获取el-form组件实例
const formRef = ref()

// 获取品牌数据
const getHasTrademark = async (page = 1) => {
  pageNo.value = page
  const res = await getHasTrademarkAPI(pageNo.value, limit.value)
  trademarkArr.value = res.data.records
  total.value = res.data.total
}

getHasTrademark()

// 改变当前页码函数
const changePageNo = async (currentPage) => {
  await getHasTrademark(currentPage)
}

// 添加品牌数据
const addTrademark = () => {
  dialogShowFlag.value = true
  // 情况收集的品牌数据
  trademarkParams.value.tmName = ''
  trademarkParams.value.logoUrl = ''
  trademarkParams.value.id = 0

  // 打开窗口时清除校验结果
  // 由于窗口页面刚加载时不一定存在，所以考虑使用可选链?或者nextTick()
  // 第一种写法
  // formRef.value?.clearValidate('tmName')
  // formRef.value?.clearValidate('logoUrl')
  // 第二种写法nextTick()
  nextTick(() => {
    formRef.value.clearValidate(['tmName', 'logoUrl'])
  })
}

// 修改品牌数据
const updateTrademark = (row) => {
  dialogShowFlag.value = true
  console.log(row)
  Object.assign(trademarkParams.value, row)
  // trademarkParams.value.tmName = row.tmName
  // trademarkParams.value.logoUrl = row.logoUrl
  // trademarkParams.value.id = row.id
  nextTick(() => {
    formRef.value.clearValidate(['tmName', 'logoUrl'])
  })
}

const confirm = async () => {
  // 在发请求之前，对整个表单进行校验
  await formRef.value.validate()
  let res = await addorUpdateTrademarkAPI(trademarkParams.value)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: trademarkParams.value.id ? '修改品牌成功' : '添加品牌成功',
    })
    dialogShowFlag.value = false
    getHasTrademark(trademarkParams.value.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: trademarkParams.value.id ? '修改品牌失败' : '添加品牌失败',
    })
  }
}

// 上传图片组件，上传图片之前触发的钩子函数
const beforeAvatarUpload = (rawFile) => {
  if (
    rawFile.type === 'image/png' ||
    rawFile.type === 'image/jpeg' ||
    rawFile.type === 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '图片不得大于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传文件应为png/jpeg/gif',
    })
    return false
  }
}

// 上传图片组件，图片上传成功触发的钩子函数
const handleAvatarSuccess = (response) => {
  console.log(response)
  trademarkParams.value.logoUrl = response.data
  // 图片上传成功，清除对图片的校验结果
  formRef.value.clearValidate('logoUrl')
}

// 品牌名校验方法
const validatorTmName = (rule, value, callback) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    // 校验未通过的错误提示信息
    callback(new Error('品牌名称需不少于两位'))
  }
}

// logo校验方法
const validatorLogoUrl = (rule, value, callback) => {
  if (value) {
    callback()
  } else {
    callback(new Error('图片务必上传'))
  }
}

// 表单校验规则
const rules = {
  tmName: [
    // required: 这个字段务必校验，表单项前面出现五角星
    // trigger；代表触发校验规则时机[blur,change]
    { required: true, trigger: blur, validator: validatorTmName },
  ],
  logoUrl: [
    {
      required: true,
      validator: validatorLogoUrl,
    },
  ],
}

// 删除品牌函数
const deleteTrademark = async (id) => {
  let res = await deleteTrademarkAPI(id)
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除品牌成功',
    })
    getHasTrademark(
      trademarkArr.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
</script>

<template>
  <div>
    <el-card>
      <el-button
        type="primary"
        size="default"
        icon="Plus"
        @click="addTrademark"
      >
        添加品牌
      </el-button>
      <el-table border style="margin: 10px 0" :data="trademarkArr">
        <el-table-column
          label="品牌"
          width="80px"
          align="center"
          type="index"
        ></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="品牌LOGO">
          <template #default="{ row }">
            <img
              :src="row.logoUrl"
              alt=""
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column label="品牌操作">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="default"
              icon="Edit"
              @click="updateTrademark(row)"
            ></el-button>

            <el-popconfirm
              title="您确定要删除该品牌吗？"
              icon="Delete"
              @confirm="deleteTrademark(row.id)"
            >
              <template #reference>
                <el-button
                  type="primary"
                  size="default"
                  icon="Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器组件
      paganation
        v-model:current-page:设置分页器当前页码
        v-model:page-size:设置每一页展示数据条数
        page-sizes: 设置下拉菜单数据
        background: 设置分页器按钮的背景颜色
        layout: 可以设置分页器六个字组件排列布局的顺序
    -->
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        @change="changePageNo"
      ></el-pagination>
    </el-card>

    <el-dialog
      :title="trademarkParams.id ? '修改品牌' : '添加品牌'"
      v-model="dialogShowFlag"
    >
      <el-form
        style="width: 80%"
        :model="trademarkParams"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input
            placeholder="请您输入品牌名称"
            v-model="trademarkParams.tmName"
          ></el-input>
        </el-form-item>

        <el-form-item label="品牌logo" label-width="100px" prop="logoUrl">
          <!-- upload组件属性：
        action 图片上传路径,需要带上/api，我们设置的代理服务器不负责发送这次post请求
        before-upload 上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传。
      -->
          <el-upload
            class="avatar-uploader"
            action="/api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkParams.logoUrl"
              :src="trademarkParams.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogShowFlag = false">取消</el-button>
        <el-button type="primary" @click="confirm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
